<template lang="html">
  <div flex="box:first" class="wh100 system-user">
    <div class="tree-wrap p10">
      <el-tree
        ref="orgTree"
        lazy
        node-key="id"
        :highlight-current="true"
        :props="{
          children: 'childList',
          label: 'shortName',
          isLeaf: 'leaf',
        }"
        :load="loadOrgNode"
        @node-click="handleNodeClick"
      />
    </div>

    <div class="flex1 relative">
      <d2-container type="full-left-right">
        <page-header slot="header" ref="pageHeader" @doSearch="doSearch" @doReset="rightReset" />

        <!-- 中间内容容器 -->
        <div v-loading="loading" class="loading-wrapper">
          <!-- 中间内容区域 -->
          <div
            v-if="$_has_one_in_many(['userAdd', 'userImport', 'userDataAccess', 'userRoleAccess'])"
            class="mb10"
          >
            <el-button v-has="'userAdd'" icon="el-icon-plus" type="primary" @click="doAdd"
              >新增</el-button
            >
            <el-button v-has="'userImport'" icon="el-icon-upload2" @click="doImport"
              >导入</el-button
            >
            <el-button
              v-has="'userDataAccess'"
              :disabled="!multipleSelection.length"
              @click="setDataAccess"
              >数据权限
            </el-button>
            <el-button
              v-has="'userRoleAccess'"
              :disabled="!multipleSelection.length"
              @click="setRoleAccess"
              >角色权限
            </el-button>
            <el-button v-has="'userDelMany'" :disabled="!multipleSelection.length" @click="delMany"
              >批量删除</el-button
            >
          </div>

          <el-table
            ref="multipleTable"
            border
            stripe
            tooltip-effect="dark"
            style="width: 100%"
            :data="tableData"
            @selection-change="(val) => (multipleSelection = val)"
          >
            <el-table-column
              v-if="$_has_one_in_many(['userDataAccess', 'userRoleAccess', 'userDelMany'])"
              type="selection"
              width="55"
              disabled="true"
              align="center"
              :selectable="({ state }) => state === '0'"
            />

            <el-table-column
              prop="userName"
              label="登录名"
              align="center"
              show-overflow-tooltip
              min-width="160"
            />
            <el-table-column
              prop="nickName"
              label="姓名"
              align="center"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              prop="deptName"
              label="部门"
              align="center"
              show-overflow-tooltip
              min-width="160"
            />
            <el-table-column
              v-if="$_has('userEnableDisable')"
              label="用户状态"
              align="center"
              width="120"
            >
              <template slot-scope="{ row }">
                <el-switch
                  v-model="row.state"
                  active-value="1"
                  inactive-value="0"
                  @change="statusChange(row)"
                />
              </template>
            </el-table-column>
         <!--   <el-table-column prop="gender" label="性别" align="center" min-width="160">
              <template slot-scope="{ row }">
                {{ userGenderOptions.find((item) => item.value === row.gender + "")?.name }}
              </template>
            </el-table-column>-->
            <el-table-column prop="createTime" label="创建时间" align="center" min-width="160" />
            <el-table-column
              v-if="$_has_one_in_many(['userEdit', 'userSee', 'userResetPass', 'userDel'])"
              label="操作"
              align="center"
              fixed="right"
              width="210"
            >
              <template slot-scope="{ row }">
                <el-button v-has="'userSee'" type="text" @click="doSee(row)">查看</el-button>
                <el-button
                  v-if="row.state !== '1'"
                  v-has="'userEdit'"
                  type="text"
                  @click="doEdit(row)"
                  >修改</el-button
                >
                <el-button v-has="'userResetPass'" type="text" @click="resetPass(row)"
                  >重置密码</el-button
                >
                <el-button
                  v-if="row.state !== '1'"
                  v-has="'userDel'"
                  type="text"
                  class="danger"
                  @click="doDel(row)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 重置密码 -->
        <pass-dialog :currentRowObj="currentRowObj" :dialogVisible.sync="passDialogVisible" />

        <!-- 新增、编辑、查看用户 -->
        <user-dialog
          :dialogVisible.sync="userDialogVisible"
          :currentRowObj="currentRowObj"
          :isCheck="isCheck"
          :deptStr="deptStr"
          @success="getTableData"
        />

        <!-- 导入弹窗 -->
        <file-import-dialog
          :dialogVisible.sync="fileImportDialogVisible"
          dialogTitle="用户导入"
          action="sys/user/import"
          importTemplateType="1"
          @success="getTableData"
        />

        <!-- 数据权限 -->
        <data-access-draw
          :dialogVisible.sync="dataAccessDrawVisible"
          :multipleSelection="multipleSelection"
          @success="getTableData"
        />

        <!-- 角色权限 -->
        <role-access-draw
          :dialogVisible.sync="roleAccessDrawVisible"
          :multipleSelection="multipleSelection"
          @success="getTableData"
        />

        <!-- 底部分页 -->
        <footer-page
          slot="footer"
          :pageSize="pageSize"
          :currentPage="currentPage"
          :total="total"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
        />
      </d2-container>
    </div>
  </div>
</template>

<script>
import PageHeader from "./components/page-header";
import PassDialog from "./components/pass-dialog";
import UserDialog from "./components/user-dialog";
import DataAccessDraw from "./components/data-access-draw";
import RoleAccessDraw from "./components/role-access-draw";
import FileImportDialog from "components/file-import-dialog";
import tableMixinKeepAlive from "mixins/tableMixinKeepAlive";
import organizeSimpleTreeMixins from "mixins/organizeSimpleTreeMixins";
import { UserList, UserDel, UserChangeStatus, UserdeleteUsers } from "api/sys/user";
import { DictKeys } from "api/sys/dict";
import { OrganizeTree } from "api/sys/organize";

export default {
  name: "system-user",
  components: {
    PageHeader,
    PassDialog,
    UserDialog,
    DataAccessDraw,
    RoleAccessDraw,
    FileImportDialog,
  },
  mixins: [tableMixinKeepAlive, organizeSimpleTreeMixins],
  data() {
    return {
      // 选中的部门数据
      deptStr: "",
      multipleSelection: [],
      // 性别
      userGenderOptions: [],
      // 重置密码的开关
      passDialogVisible: false,
      // 用户新增、编辑的开关
      userDialogVisible: false,
      // 列表接口名
      getTableListSyncMethod: UserList,
      // 导入弹窗开关
      fileImportDialogVisible: false,
      // 数据权限draw开关
      dataAccessDrawVisible: false,
      // 角色权限draw开关
      roleAccessDrawVisible: false,
      // 当前行数据
      currentRowObj: null,
      // 是否为查看
      isCheck: false,
      loading: false,
      // 左侧树选中id
      deptId: "",
    };
  },
  created() {
    this._DictKeys();
  },
  methods: {
    /**
     * 搜索数据格式化
     */
    searchObjFormat() {
      return {
        ...this.searchObj,
        deptId: this.deptId,
      };
    },
    /**
     * 获取区域层级
     */
    async _DictKeys() {
      try {
        this.wrapperLoading = true;
        const data = await DictKeys("user_gender");
        if (data) {
          const { user_gender: userGender } = data;
          this.userGenderOptions = userGender;
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.wrapperLoading = false;
      }
    },
    /**
     * 列表数据格式化
     */
    tableDataFormat(data) {
      data.map((item) => {
        const { state } = item;
        item.originStatus = state;
      });
      return data;
    },
    /**
     * 启用、停用
     */
    async statusChange(row) {
      const { nickName, originStatus, id } = row;
      // 重置回去
      row.state = originStatus;
      const flag = row.state === "1";
      const str = flag ? "停用" : "启用";
      try {
        await this.$myConfirm(`<b>${str}</b>用户: <b>${nickName}</b> `);
        await UserChangeStatus(id);
        const newStatus = flag ? "0" : "1";
        row.state = row.originStatus = newStatus;
        this.$message.success(`用户${str}成功`);
      } catch (e) {
        console.log(e);
        this.$message.error(`用户${str}失败`);
      }
    },
    /**
     * 新增
     */
    doAdd() {
      this.isCheck = false;
      this.currentRowObj = null;
      this.userDialogVisible = true;
    },
    /**
     * 编辑
     */
    doEdit(row) {
      this.isCheck = false;
      this.currentRowObj = row;
      this.userDialogVisible = true;
    },
    /**
     * 查看
     */
    doSee(row) {
      this.isCheck = true;
      this.currentRowObj = row;
      this.userDialogVisible = true;
    },
    /**
     * 重置密码
     */
    resetPass(row) {
      this.currentRowObj = row;
      this.passDialogVisible = true;
    },
    /**
     * 删除
     */
    async doDel({ id }) {
      await this.$myConfirm("删除本用户");
      try {
        await UserDel(id);
        this.$message.success("用户删除成功");
        this.getTableData();
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 批量删除
     */
    async delMany() {
      await this.$myConfirm("批量删除这些用户");
      try {
        const uidList = this.multipleSelection.map((item) => item.id);
        await UserdeleteUsers({ uidList });
        this.$message.success("用户批量删除成功");
        this.getTableData();
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 导入
     */
    doImport() {
      this.fileImportDialogVisible = true;
    },
    /**
     * 设置数据权限
     */
    setDataAccess() {
      this.dataAccessDrawVisible = true;
    },
    /**
     * 设置角色权限
     */
    setRoleAccess() {
      this.roleAccessDrawVisible = true;
    },
    /**
     * 加载部门数据
     */
    async loadOrgNode(node, resolve) {
      // 第一次加载数据
      if (node.level === 0) {
        let data = await this._OrganizeTree();
        const { length } = data;
        if (length) {
          data = this.treeDataFormat(data);
        }
        return resolve(data);
      } else {
        const {
          data: { id },
        } = node;
        const data = await this._OrganizeTree({ parentId: id });
        return resolve(this.treeDataFormat(data));
      }
    },
    /**
     * 获取左侧树形结构的数据
     */
    async _OrganizeTree({ parentId = 0 } = {}) {
      try {
        const data = await OrganizeTree(parentId);
        return data || [];
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 树形数据格式化
     */
    treeDataFormat(arr) {
      arr.map((item) => {
        const { subCount, areaId } = item;
        item.leaf = !subCount;
        if (areaId) {
          item.areaId = areaId;
        }
      });
      return arr.sort((a, b) => a.sortBy - b.sortBy);
    },
    /**
     * 树节点的点击事件
     */
    handleNodeClick(data) {
      const { id, shortName } = data;
      this.deptStr = JSON.stringify([{ name: shortName, value: id }]);
      this.deptId = id;
      this.getTableData();
    },
    /**
     * 重置
     */
    rightReset() {
      this.deptId = "";
      this.$refs.orgTree.setCurrentKey(null);
      this.doReset();
    },
  },
};
</script>

<style lang="scss" scoped>
.system-user {
  .tree-wrap {
    width: 300px;
    border-right: 1px solid $border-color;
  }
}
</style>
